import shanxi from "./shanxi.json";
var myImageSource = "";
var imageLayer = "";

var listaddSource = [];
var listaddLayer = [];
var wendu = [];

import {
  wintertemperature,
  springtemperature,
  temperaturetemperature,
  autumntemperature,
  precipitation,
  humidity,
  windpower,
} from "./water";
var day = new Date();
var month = day.getMonth() + 1;

if (month === 1 || month === 2 || month === 12) {
  wendu = wintertemperature;
} else if (month >= 3 && month <= 5) {
  // wendu = springtemperature;
  wendu = wintertemperature;
} else if (month >= 6 && month <= 8) {
  wendu = temperaturetemperature;
} else if (month >= 9 && month <= 11) {
  wendu = autumntemperature;
}
function search(keywords, map) {
  SGMap.plugin(["SGMap.DistrictTask"]).then(function (res) {
    var districtTask = new SGMap.DistrictTask();
    districtTask
      .searchDistrict({
        keyword: "山西省",

        pageIndex: 1,
        pageSize: 10,
        extension: true,
        subdistrict: 0,
      })
      .then(function (result) {
        if (!result.data) return;
        result = result.data;
        console.log(result.data);
        if (!result.districts) {
          error("查询结果为空！");
          return;
        }
        console.log("districts", result.districts);
        var features = [];

        var provinceFeatures = [],
          cityFeatures = [],
          countyFeatures = [],
          townFeatures = [],
          villageFeatures = [];

        for (var i = 0; i < result.districts.length; i++) {
          switch (result.districts[i].level) {
            case "province":
              provinceFeatures.push({
                type: "Feature",
                geometry: result.districts[i].shape,
              });
              break;
            case "city":
              cityFeatures.push({
                type: "Feature",
                geometry: result.districts[i].shape,
              });
              break;
            case "county":
              countyFeatures.push({
                type: "Feature",
                geometry: result.districts[i].shape,
              });
              break;
          }
        }

        // 更新图层数据

        map.getSource("province-line").setData({
          type: "FeatureCollection",
          features: provinceFeatures,
        });

        // 更新图层数据
        // map.getSource('province-polygon').setData({
        //   type: 'FeatureCollection',
        //   features: provinceFeatures,
        // })
        // map.getSource('province-line').setData({
        //   type: 'FeatureCollection',
        //   features: provinceFeatures,
        // })
        // map.getSource('city-polygon').setData({
        //   type: 'FeatureCollection',
        //   features: cityFeatures,
        // })
        // map.getSource('city-line').setData({
        //   type: 'FeatureCollection',
        //   features: cityFeatures,
        // })
        // map.getSource('county-polygon').setData({
        //   type: 'FeatureCollection',
        //   features: countyFeatures,
        // })
        // map.getSource('county-line').setData({
        //   type: 'FeatureCollection',
        //   features: countyFeatures,
        // })
      });
  });
  // 获取查询条件

  // 查询行政区划详细信息
}
function initLayer(keywords, map) {
  // 显示查询行政区划范围
  // 省：蓝线
  map.addLayer({
    id: "province-line",
    type: "line",
    source: {
      type: "geojson",
      data: {
        type: "FeatureCollection",
        features: [],
      },
    },
    layout: {
      "line-cap": "round",
      "line-join": "round",
    },
    paint: {
      "line-color": "#3995ea",
      "line-width": 2,
    },
  });
  //分解
  //   map.addLayer({
  //     id: 'province-polygon',
  //     type: 'fill',
  //     source: {
  //       type: 'geojson',
  //       data: {
  //         type: 'FeatureCollection',
  //         features: [],
  //       },
  //     },
  //     paint: {
  //       'fill-color': '#206bf5',
  //       'fill-opacity': 0.3,
  //     },
  //   })
  //   map.addLayer({
  //     id: 'province-line',
  //     type: 'line',
  //     source: {
  //       type: 'geojson',
  //       data: {
  //         type: 'FeatureCollection',
  //         features: [],
  //       },
  //     },
  //     layout: {
  //       'line-cap': 'round',
  //       'line-join': 'round',
  //     },
  //     paint: {
  //       'line-color': '#3995ea',
  //       'line-width': 2,
  //     },
  //   })
  //   // 市：绿面、绿线
  //   map.addLayer({
  //     id: 'city-polygon',
  //     type: 'fill',
  //     source: {
  //       type: 'geojson',
  //       data: {
  //         type: 'FeatureCollection',
  //         features: [],
  //       },
  //     },
  //     paint: {
  //       'fill-color': '#206bf5',
  //       'fill-opacity': 0.3,
  //     },
  //   })
  //   map.addLayer({
  //     id: 'city-line',
  //     type: 'line',
  //     source: {
  //       type: 'geojson',
  //       data: {
  //         type: 'FeatureCollection',
  //         features: [],
  //       },
  //     },
  //     paint: {
  //       'line-color': '#206bf5',
  //       'line-width': 3,
  //     },
  //   })
  //   // 区/县：黄面、黑线
  //   map.addLayer({
  //     id: 'county-polygon',
  //     type: 'fill',
  //     source: {
  //       type: 'geojson',
  //       data: {
  //         type: 'FeatureCollection',
  //         features: [],
  //       },
  //     },
  //     paint: {
  //       'fill-color': '#f2f520',
  //       'fill-opacity': 0.7,
  //     },
  //   })
  //   map.addLayer({
  //     id: 'county-line',
  //     type: 'line',
  //     source: {
  //       type: 'geojson',
  //       data: {
  //         type: 'FeatureCollection',
  //         features: [],
  //       },
  //     },
  //     paint: {
  //       'line-color': '#888a01',
  //       'line-width': 3,
  //     },
  //   })
}
//  全部市画线
function searchAll(keywords, map) {
  var features = [];

  var provinceFeatures = [];

  var cityFeatureslist = [];
  for (var i = 0; i < shanxi.features.length; i++) {
    cityFeatureslist = shanxi.features[i].geometry;
    provinceFeatures.push({
      type: "Feature",
      geometry: cityFeatureslist,
    });
  }

  //   更新图层数据
  console.log(provinceFeatures);
  map.getSource("province-line").setData({
    type: "FeatureCollection",
    features: provinceFeatures,
  });
  //   map.getSource('province-polygon').setData({
  //     type: 'FeatureCollection',
  //     features: provinceFeatures,
  //   })

  // 获取查询条件

  // 查询行政区划详细信息
}
//全部市画线
function initLayerAll(keywords, map) {
  // 显示查询行政区划范围
  //分解

  map.addLayer({
    id: "province-line",
    type: "line",
    source: {
      type: "geojson",
      data: {
        type: "FeatureCollection",
        features: [],
      },
    },
    layout: {
      "line-cap": "round",
      "line-join": "round",
    },
    paint: {
      "line-color": "#3995ea",
      "line-width": 2,
    },
  });
  //   map.addLayer({
  //     id: 'province-polygon',
  //     type: 'line',
  //     source: {
  //       type: 'geojson',
  //       data: {
  //         type: 'FeatureCollection',
  //         features: [],
  //       },
  //     },
  //     layout: {
  //       'line-cap': 'round',
  //       'line-join': 'round',
  //     },
  //     paint: {
  //       'line-color': '#3995ea',
  //       'line-width': 2,
  //     },
  //   })
  // 市：绿面、绿线
  map.addLayer({
    id: "city-polygon",
    type: "fill",
    source: {
      type: "geojson",
      data: {
        type: "FeatureCollection",
        features: [],
      },
    },
    paint: {
      "fill-color": "#206bf5",
      "fill-opacity": 0.3,
    },
  });
  map.addLayer({
    id: "city-line",
    type: "line",
    source: {
      type: "geojson",
      data: {
        type: "FeatureCollection",
        features: [],
      },
    },
    paint: {
      "line-color": "#206bf5",
      "line-width": 3,
    },
  });
  // 区/县：黄面、黑线
  map.addLayer({
    id: "county-polygon",
    type: "fill",
    source: {
      type: "geojson",
      data: {
        type: "FeatureCollection",
        features: [],
      },
    },
    paint: {
      "fill-color": "#f2f520",
      "fill-opacity": 0.7,
    },
  });
  map.addLayer({
    id: "county-line",
    type: "line",
    source: {
      type: "geojson",
      data: {
        type: "FeatureCollection",
        features: [],
      },
    },
    paint: {
      "line-color": "#888a01",
      "line-width": 3,
    },
  });
}
//全部市画面
function searchAllpoly(keywords, map) {
  var features = [];

  var provinceFeatures = [];

  var cityFeatureslist = [];
  for (var i = 0; i < shanxi.features.length; i++) {
    cityFeatureslist = shanxi.features[i].geometry;
    provinceFeatures.push({
      type: "Feature",
      geometry: cityFeatureslist,
    });
  }

  //   更新图层数据

  map.getSource("province-line").setData({
    type: "FeatureCollection",
    features: provinceFeatures,
  });
  map.getSource("province-polygon").setData({
    type: "FeatureCollection",
    features: provinceFeatures,
  });

  // 获取查询条件

  // 查询行政区划详细信息
}
//全部市画面
function initLayerAllpoly(keywords, map1) {
  // 显示查询行政区划范围
  //分解

  map.addLayer({
    id: "province-line",
    type: "line",
    source: {
      type: "geojson",
      data: {
        type: "FeatureCollection",
        features: [],
      },
    },
    layout: {
      "line-cap": "round",
      "line-join": "round",
    },
    paint: {
      "line-color": "#3995ea",
      "line-width": 2,
    },
  });
  map.addLayer({
    id: "province-polygon",
    type: "fill",
    source: {
      type: "geojson",
      data: {
        type: "FeatureCollection",
        features: [],
      },
    },
    paint: {
      "fill-color": "#206bf5",
      "fill-opacity": 0.3,
    },
  });
  // 市：绿面、绿线
  map.addLayer({
    id: "city-polygon",
    type: "fill",
    source: {
      type: "geojson",
      data: {
        type: "FeatureCollection",
        features: [],
      },
    },
    paint: {
      "fill-color": "#206bf5",
      "fill-opacity": 0.3,
    },
  });
  map.addLayer({
    id: "city-line",
    type: "line",
    source: {
      type: "geojson",
      data: {
        type: "FeatureCollection",
        features: [],
      },
    },
    paint: {
      "line-color": "#206bf5",
      "line-width": 3,
    },
  });
  // 区/县：黄面、黑线
  map.addLayer({
    id: "county-polygon",
    type: "fill",
    source: {
      type: "geojson",
      data: {
        type: "FeatureCollection",
        features: [],
      },
    },
    paint: {
      "fill-color": "#f2f520",
      "fill-opacity": 0.7,
    },
  });
  map.addLayer({
    id: "county-line",
    type: "line",
    source: {
      type: "geojson",
      data: {
        type: "FeatureCollection",
        features: [],
      },
    },
    paint: {
      "line-color": "#888a01",
      "line-width": 3,
    },
  });
}
function searchshi(keywords, map1) {
  SGMap.plugin(["SGMap.DistrictTask"]).then(function (res) {
    var districtTask = new SGMap.DistrictTask();
    districtTask
      .searchDistrict({
        keyword: keywords,

        pageIndex: 1,
        pageSize: 10,
        extension: true,
        subdistrict: 0,
      })
      .then(function (result) {
        if (!result.data) return;
        result = result.data;
        if (!result.districts) {
          error("查询结果为空！");
          return;
        }

        var features = [];

        var provinceFeatures = [],
          cityFeatures = [],
          countyFeatures = [],
          townFeatures = [],
          villageFeatures = [];

        for (var i = 0; i < result.districts.length; i++) {
          switch (result.districts[i].level) {
            case "province":
              provinceFeatures.push({
                type: "Feature",
                geometry: result.districts[i].shape,
              });
              break;
            case "city":
              cityFeatures.push({
                type: "Feature",
                geometry: result.districts[i].shape,
              });
              break;
            case "county":
              countyFeatures.push({
                type: "Feature",
                geometry: result.districts[i].shape,
              });
              break;
          }
        }
        console.log(cityFeatures);
        // 更新图层数据
        map1.getSource("province-polygon").setData({
          type: "FeatureCollection",
          features: provinceFeatures,
        });
        map1.getSource("province-line").setData({
          type: "FeatureCollection",
          features: provinceFeatures,
        });

        map1.getSource("city-polygon").setData({
          type: "FeatureCollection",
          features: cityFeatures,
        });
        map1.getSource("city-line").setData({
          type: "FeatureCollection",
          features: cityFeatures,
        });
        map1.getSource("county-polygon").setData({
          type: "FeatureCollection",
          features: countyFeatures,
        });
        map1.getSource("county-line").setData({
          type: "FeatureCollection",
          features: countyFeatures,
        });
      });
  });
}
function initLayershi(keywords, map1) {
  // 显示查询行政区划范围
  // 省：蓝线
  var _this = this;
  map1.addLayer({
    id: "province-polygon",
    type: "fill",
    source: {
      type: "geojson",
      data: {
        type: "FeatureCollection",
        features: [],
      },
    },
    paint: {
      "fill-color": "#206bf5",
      "fill-opacity": 0.3,
    },
  });
  map1.addLayer({
    id: "province-line",
    type: "line",
    source: {
      type: "geojson",
      data: {
        type: "FeatureCollection",
        features: [],
      },
    },
    layout: {
      "line-cap": "round",
      "line-join": "round",
    },
    paint: {
      "line-color": "#3995ea",
      "line-width": 2,
    },
  });
  map1.addLayer({
    id: "city-polygon",
    type: "fill",
    source: {
      type: "geojson",
      data: {
        type: "FeatureCollection",
        features: [],
      },
    },
    paint: {
      "fill-color": "#206bf5",
      "fill-opacity": 0.3,
    },
  });
  map1.addLayer({
    id: "city-line",
    type: "line",
    source: {
      type: "geojson",
      data: {
        type: "FeatureCollection",
        features: [],
      },
    },
    paint: {
      "line-color": "#206bf5",
      "line-width": 3,
    },
  });
  // 区/县：黄面、黑线
  map1.addLayer({
    id: "county-polygon",
    type: "fill",
    source: {
      type: "geojson",
      data: {
        type: "FeatureCollection",
        features: [],
      },
    },
    paint: {
      "fill-color": "#d4e5f5",
      "fill-opacity": 0.7,
    },
  });
  map1.addLayer({
    id: "county-line",
    type: "line",
    source: {
      type: "geojson",
      data: {
        type: "FeatureCollection",
        features: [],
      },
    },
    paint: {
      "line-color": "#206bf5",
      "line-width": 3,
    },
  });

  // 显示查询范围
  map1.addLayer({
    id: "zoom-line",
    type: "line",
    source: {
      type: "geojson",
      data: {
        type: "FeatureCollection",
        features: [],
      },
    },
    layout: {
      "line-cap": "round",
      "line-join": "round",
    },
    paint: {
      "line-color": "#f52020",
      "line-width": 3,
    },
  });
}
function clears(map) {
  map.removeLayer("city-line");
  map.removeSource("city-line");
  map.removeLayer("city-polygon");
  map.removeSource("city-polygon");
  map.removeLayer("province-line");
  map.removeSource("province-line");
  map.removeLayer("province-polygon");
  map.removeSource("province-polygon");
  map.removeLayer("county-line");
  map.removeSource("county-line");
  map.removeLayer("county-polygon");
  map.removeSource("county-polygon");
  map.removeLayer("zoom-line");
  map.removeSource("zoom-line");
}
//克里金

function canvans(features, factorIndex, map, id) {
  var positions = [];
  //   listaddLayer = []
  //   listaddSource = []
  world[0].forEach(function (point) {
    positions.push([point[1], point[0]]);
  });

  //根据scope边界线，生成范围信息
  var xlim = [110.229593, 114.568922];
  var ylim = [34.583472, 40.739941];

  //进行克里金插值

  var canvas = document.getElementById("canvasMap");
  canvas.width = 1000;
  canvas.height = 1000;
  //var n = points.length;
  var t = []; //数值
  var x = []; //经度
  var y = []; //纬度

  for (let i = 0; i < features.length; i = i + 50) {
    let xValue = features[i].attributes.x;
    let yValue = features[i].attributes.y;
    // if (features[i].attributes.z.toString().startsWith("0.")) {
    //   features[i].attributes.z = parseFloat(1 + features[i].attributes.z.toString().substr(1));
    // }

    t.push(features[i].attributes.z.toFixed(2));

    x.push(xValue);
    y.push(yValue);
  }

  for (let i = 0; i < t.length; i++) {
    if (t[i].startsWith("0.")) {
      t[i] = "1" + t[i].substr(1);
    }
  }

  console.log(t);

  //对数据集进行训练
  var variogram = kriging.train(t, x, y, "exponential", 0, 100);

  //使用variogram对象使polygons描述的地理位置内的格网元素具备不一样的预测值,最后一个参数，是插值格点精度大小
  var grid = kriging.grid(world, variogram, (ylim[1] - ylim[0]) / 900);

  var colors = [];

  const max = Math.max(...t);
  console.log(max);
  if (factorIndex == 0) {
    const smallerThanFiveColors = wendu
      .filter((item) => {
        const interval = Number(item.interval); // 获取 interval 的数值
        return interval < max; // 判断是否满足条件
      })
      .map((item) => item.color); // 获取满足条件的颜色
    console.log(smallerThanFiveColors);
    colors = smallerThanFiveColors;
  } else if (factorIndex == 1) {
    const smallerThanFiveColors = humidity
      .filter((item) => {
        const interval = Number(item.interval); // 获取 interval 的数值
        return interval < max; // 判断是否满足条件
      })
      .map((item) => item.color); // 获取满足条件的颜色

    colors = smallerThanFiveColors;
  } else if (factorIndex == 2) {
    const smallerThanFiveColors = windpower
      .filter((item) => {
        const interval = Number(item.interval); // 获取 interval 的数值
        return interval < max; // 判断是否满足条件
      })
      .map((item) => item.color); // 获取满足条件的颜色
    if (max) colors = smallerThanFiveColors;
    const firstInterval = windpower[0].interval.replace(/[<>]/g, "");
    const lastInterval = windpower[windpower.length - 1].interval.replace(
      /[<>]/g,
      ""
    );

    const firstcolor = windpower[0].color;
    const lastcolor = windpower[windpower.length - 1].color;
    if (smallerThanFiveColors.length == 0) {
      if (max <= firstInterval) {
        colors.push(firstcolor);
      } else if (max >= lastInterval) {
        colors.push(lastcolor);
      }
    }
  } else if (factorIndex == 3) {
    const smallerThanFiveColors = precipitation
      .filter((item) => {
        const interval = Number(item.interval); // 获取 interval 的数值
        return interval < max; // 判断是否满足条件
      })
      .map((item) => item.color); // 获取满足条件的颜色

    const firstInterval = precipitation[0].interval.replace(/[<>]/g, "");
    const lastInterval = precipitation[
      precipitation.length - 1
    ].interval.replace(/[<>]/g, "");

    const firstcolor = precipitation[0].color;
    const lastcolor = precipitation[precipitation.length - 1].color;
    if (smallerThanFiveColors.length == 0) {
      if (max >= firstInterval) {
        colors.push(firstcolor);
      } else if (max <= lastInterval) {
        colors.push(lastcolor);
      }
    }
  }
  console.log(colors);
  colors = colors.reverse();

  //将得到的格网grid渲染至canvas上
  kriging.plot(canvas, grid, [xlim[0], xlim[1]], [ylim[0], ylim[1]], colors);
  var mycanvas = document.getElementById("canvasMap");
  // console.log(mycanvas.toDataURL('image/png'))
  map.addSource("myImageSource" + id, {
    type: "image", // 数据源为类型为image
    url: mycanvas.toDataURL("image/png"), // 图像地址
    coordinates: [
      // 图像显示4个点的位置信息
      [110.230982, 40.73053], // 左上
      [114.568922, 40.71503], // 右上
      [114.568922, 34.553472], // 右下
      [110.22959344, 34.56666666666667], // 左下
    ],
  });

  map.addLayer({
    id: "imageLayer" + id, // 图层名称
    type: "raster", // 显示类型为栅格
    source: "myImageSource" + id, // 与数据源ID相关联
    paint: {
      "raster-opacity": 0.7, // 设置图层透明度（0.0 - 1.0）
    },
  });

  imageLayer = "imageLayer" + id;
  myImageSource = "myImageSource" + id;

  listaddLayer.push("imageLayer" + id);

  listaddSource.push("myImageSource" + id);

  console.log(imageLayer, "1");
}

function clearcanvans(map) {
  console.log("2");
  listaddLayer.forEach((it) => {
    if (imageLayer != it) {
      map.removeLayer(it); // 删除图层
      var index = listaddLayer.indexOf(it);
      if (index > -1) {
        listaddLayer.splice(index, 1);
      }
    }
  });

  listaddSource.forEach((it) => {
    if (myImageSource != it) {
      map.removeSource(it); // 删除数据源(it) // 删除图层
      var index = listaddSource.indexOf(it);
      if (index > -1) {
        listaddSource.splice(index, 1);
      }
    }
  });
}
function allclearcanvans(map) {
  listaddLayer.forEach((it) => {
    map.removeLayer(it); // 删除图层
  });
  listaddLayer = [];

  listaddSource.forEach((it) => {
    map.removeSource(it); // 删除数据源(it) // 删除图层
  });
  listaddSource = [];
}
function bianKong() {
  listaddSource = [];
  listaddLayer = [];
}

export {
  search,
  initLayer,
  initLayerAll,
  searchAll,
  searchAllpoly,
  initLayershi,
  clears,
  searchshi,
  allclearcanvans,
  initLayerAllpoly,
  canvans,
  bianKong,
  clearcanvans,
};
